package com.demo.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.SecureRandom;
import java.util.Random;

/**
 * @author wangfengchen
 */
@Slf4j
public class RandomUtil {
  private RandomUtil() {
  }

  /**
   * 获取验证码随机数
   *
   * @param length
   * @return
   */
  public static String getRandomCode(int length) {
    String sources = "0123456789";
    Random random = new SecureRandom();
    StringBuilder sb = new StringBuilder();
    for (int j = 0; j < length; j++) {
      sb.append(sources.charAt(random.nextInt(9)));
    }
    return sb.toString();
  }

  private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  /**
   * 获取随机长度的串
   *
   * @param length
   * @return
   */
  public static String getStringNumRandom(int length) {
    //生成随机数字和字母,
    Random random = new SecureRandom();
    StringBuilder saltString = new StringBuilder(length);
    for (int i = 1; i <= length; ++i) {
      saltString.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
    }
    return saltString.toString();
  }

  public static void main(String[] args) {
    log.info(getRandomCode(6));
    log.info(getStringNumRandom(6));
  }
}
